package com.thread.book.book2;

import java.util.concurrent.TimeUnit;

public class Book04 {
    public static void main(String[] args) throws Exception {
        Runner one = new Runner();
        Thread countThread = new Thread(one, "CountThread");
        countThread.start();
        // 睡眠1秒，main线程对CountThread进行中断，使CountThread能够感知中断而结束
        TimeUnit.SECONDS.sleep(1);
        countThread.interrupt();//中断线程
        Runner two = new Runner();
        new Thread(two, "CountThread").start();
        // 睡眠1秒，main线程对Runner two进行取消，使CountThread能够感知on为false而结束
        TimeUnit.SECONDS.sleep(1);
        two.cancel(); //线程终止,这种方法更好,程序有机会去清理资源,而不是直接停止
    }

    private static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true; //线程是否继续标志

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }
            System.out.println("Count i = " + i);
        }

        public void cancel() {
            on = false;
        }
    }
}
